/**
 * @Author: wangtao
 * @Date: 2020-06-29 16:32:41
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-03-20 11:49:43
 * @Description: file content
 */

import React, { Component } from 'react';
import {
  Image,
  Keyboard,
  Modal,
  PixelRatio,
  ScrollView,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import {
  fontColorBlack,
  fontColorCoffee,
  fontColorDeepGray,
  fontColorSecDeepGray,
  mainBgColorBlack,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  screenHeight,
  screenWidth,
  splitLineColorLightGray,
} from '../../../../../common/styles';
import { _, Button, msg } from '../../../../../common';
import SelectItem from './select-item';
import { fetchUnitList } from '../../../../../api/source-release';
import { iconBottom, iconTop } from '../../../../../image';

const { Submit } = Button;

export default class HopeFreight extends Component {
  constructor(props) {
    super(props);
    this.state = {
      freightConsignorPer: null, // 运费单价货主
      freightUnit: [], // 运费单位 每吨多少 每趟多少
      messageCost: null, // 信息费
      lossesAmount: null, // 耗损费
      lossesUnit: [], // 耗损费单位
      unitList: [], // 单位选项
      isTax: 1,
      keyboardHeight: '', // 键盘高度
      isSubmit: false,
      isNeedMoreInfo: false,
    };
  }

  componentDidMount() {
    const { supply } = this.props;
    const {
      freightConsignorPer,
      freightUnit,
      lossesAmount,
      lossesUnit,
      messageCost,
      isTax
    } = supply;

    fetchUnitList().then((res) => {
      if (res.success) {
        this.setState({
          unitList: res.data,
          freightConsignorPer,
          freightUnit: [freightUnit || res.data[0].name],
          lossesAmount,
          lossesUnit: [lossesUnit],
          messageCost,
          isNeedMoreInfo: Boolean(parseFloat(lossesAmount)) || Boolean(parseFloat(messageCost)),
          isTax
        });
      }
    });

    // 监听键盘
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardWillShow',
      this._keyboardDidShow.bind(this),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardWillHide',
      this._keyboardDidHide.bind(this),
    );
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  render() {
    const { onChangeModal, onChangeVal } = this.props;
    const {
      freightConsignorPer,
      freightUnit,
      lossesAmount,
      lossesUnit,
      messageCost,
      unitList,
      isSubmit,
      keyboardHeight,
      isNeedMoreInfo,
      isTax
    } = this.state;
    return (
      <Modal
        animationType='slide'
        transparent
        visible
        onRequestClose={() => {
          onChangeModal({ type: 'hopeFreightIsShow', val: false });
        }}
        onShow={() => {
        }}
      >
        <TouchableOpacity
          style={styles.mask}
          onPress={() => {
            onChangeModal({ type: 'hopeFreightIsShow', val: false });
          }}
        />
        <View
          style={[
            styles.infoContainer,
            { marginBottom: Number(this.state.keyboardHeight) },
          ]}
        >
          <View style={styles.header}>
            <TouchableOpacity
              style={styles.cancel}
              onPress={() => {
                onChangeModal({ type: 'hopeFreightIsShow', val: false });
              }}
            >
              <Text style={{ fontSize: px2dp(32), color: fontColorSecDeepGray }}>
                取消
              </Text>
            </TouchableOpacity>
            <Text
              style={{
                fontSize: px2dp(32),
                color: fontColorBlack,
                fontWeight: 'bold',
              }}
            >
              期望运费
            </Text>
            <Submit
              text='确定'
              boxStyle={{
                width: px2dp(104),
                height: px2dp(60),
                borderRadius: px2dp(8),
                position: 'absolute',
                right: px2dp(28),
              }}
              disabled={false}
              onClick={() => {
                this.submit();
              }}
            />
          </View>
          <View style={[styles.editContainer, {}]}>
            <ScrollView showsVerticalScrollIndicator={false}>
              {/* 运费 */}
              <View style={styles.packing}>
                <View style={styles.itemHeader}>
                  <Text
                    style={{
                      fontSize: px2dp(28),
                      fontWeight: 'bold',
                      color: mainBgColorBlack,
                    }}
                  >
                    运费
                    {' '}
                    <Text
                      style={{
                        fontSize: px2dp(28),
                        fontWeight: 'normal',
                        color: !isSubmit ? fontColorSecDeepGray : 'red',
                      }}
                    >
                      (必填、数量和单位)
                    </Text>
                  </Text>
                  <View style={styles.itemHeader}>
                    <Text
                      style={{
                        fontSize: px2dp(28),
                        fontWeight: 'normal',
                        color: fontColorSecDeepGray,
                      }}
                    >
                      是否含税
                    </Text>
                    <Switch
                      trackColor={{
                        false: '#E6E6E5',
                        true: fontColorCoffee,
                      }}
                      value={isTax === 1}
                      onValueChange={value => {
                        this.setState({ isTax: value ? 1 : 2 });
                      }}
                      testID='one'
                      thumbColor='#fff'
                    />
                  </View>
                </View>

                <View style={styles.itemInput}>
                  <TextInput
                    placeholder='请输入运费单价'
                    style={[
                      styles.goodsWrapPriceTextInput,
                      { color: fontColorBlack },
                    ]}
                    defaultValue={freightConsignorPer}
                    value={freightConsignorPer}
                    underlineColorAndroid='transparent'
                    onChangeText={(val) => {
                      // 清理非数字.
                      val = _.clearNoNum(val);
                      // 保留两位小数
                      val = _.clearDotNumTo2(val);
                      if (val.length > 8) {
                        return;
                      }
                      this.onChange('freightConsignorPer', val);
                    }}
                    keyboardType={
                      Platform.OS === 'android' ? 'numeric' : 'decimal-pad'
                    }
                    onBlur={() => {
                    }}
                  />
                  {!!freightUnit.length && !!freightUnit[0] && (
                    <Text style={{ color: fontColorDeepGray }}>
                      元/
                      {freightUnit}
                    </Text>
                  )}
                </View>

                <View style={styles.itemSelect}>
                  {!!unitList.length &&
                  unitList.map((item) => {
                    return (
                      <SelectItem
                        name={item.name}
                        type='freightUnit'
                        value={item.name}
                        activeVal={freightUnit}
                        maxLength={1}
                        onChange={(type, value) =>
                          this.onChange(type, [value])}
                      />
                    );
                  })}
                </View>
              </View>
              {isNeedMoreInfo && this.renderMoreInfo()}
              <TouchableOpacity
                activeOpacity={0.8}
                style={styles.moreInfo}
                onPress={() => this.setState({ isNeedMoreInfo: !isNeedMoreInfo })}
              >
                <Text style={styles.moreInfoText}>{isNeedMoreInfo ? '收起' : '更多信息'}</Text>
                <Image
                  source={isNeedMoreInfo ? iconTop : iconBottom}
                  style={styles.moreInfoImage}
                />
              </TouchableOpacity>
            </ScrollView>
          </View>
        </View>
      </Modal>
    );
  }

  _keyboardDidShow(e) {
    this.setState({
      keyboardHeight: e.startCoordinates.height,
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }

  renderMoreInfo = () => {
    const { lossesAmount, lossesUnit, messageCost, unitList, isSubmit } = this.state;
    return (
      <>
        {/* 信息费 */}
        <View style={styles.packing}>
          <View style={styles.itemHeader}>
            <Text
              style={{
                fontSize: px2dp(28),
                fontWeight: 'bold',
                color: mainBgColorBlack,
              }}
            >
              信息费
              {' '}
            </Text>
          </View>

          <View style={styles.itemInput}>
            <TextInput
              placeholder='请输入信息费'
              style={[
                styles.goodsWrapPriceTextInput,
                { color: fontColorBlack },
              ]}
              defaultValue={messageCost}
              value={messageCost}
              underlineColorAndroid='transparent'
              onChangeText={(val) => {
                // 清理非数字.
                val = _.clearNoNum(val);
                // 保留两位小数
                val = _.clearDotNumTo2(val);
                if (val.length > 8) {
                  return;
                }
                this.onChange('messageCost', val);
              }}
              keyboardType={Platform.OS === 'android' ? 'numeric' : 'decimal-pad'}
              onBlur={() => {
              }}
            />
            <Text style={{ color: fontColorDeepGray }}>元</Text>
          </View>
        </View>
        {/* 损耗费 */}
        <View style={styles.packing}>
          <View style={styles.itemHeader}>
            <Text
              style={{
                fontSize: px2dp(28),
                fontWeight: 'bold',
                color: mainBgColorBlack,
              }}
            >
              损耗费
              {' '}
            </Text>
          </View>

          <View style={styles.itemInput}>
            <TextInput
              placeholder='请输入损耗单价'
              style={[
                styles.goodsWrapPriceTextInput,
                { color: fontColorBlack },
              ]}
              defaultValue={lossesAmount}
              value={lossesAmount}
              underlineColorAndroid='transparent'
              onChangeText={(val) => {
                // 清理非数字.
                val = _.clearNoNum(val);
                // 保留两位小数
                val = _.clearDotNumTo2(val);
                if (val.length > 8) {
                  return;
                }
                this.onChange('lossesAmount', val);
                this.setState({
                  lossesUnit: val ? [lossesUnit[0] || unitList[0].name] : [],
                });
              }}
              keyboardType={
                Platform.OS === 'android' ? 'numeric' : 'decimal-pad'
              }
              onBlur={() => {
              }}
            />
            {!!lossesUnit.length && !!lossesUnit[0] && (
              <Text style={{ color: fontColorDeepGray }}>
                元/
                {lossesUnit}
              </Text>
            )}
          </View>

          <View style={styles.itemSelect}>
            {!!unitList.length &&
            unitList.map((item) => {
              return (
                <SelectItem
                  name={item.name}
                  type='lossesUnit'
                  value={item.name}
                  activeVal={lossesUnit}
                  maxLength={1}
                  onChange={(type, value) => {
                    const { lossesAmount } = this.state;
                    if (lossesAmount) {
                      this.onChange(type, [value]);
                    }
                  }}
                />
              );
            })}
          </View>
        </View>
      </>
    );
  }

  // 改变
  onChange = (type, val) => {
    this.setState({ [type]: val });
  };

  // 提交
  submit = () => {
    const { onChangeVal, onChangeModal } = this.props;
    const {
      freightConsignorPer,
      freightUnit,
      lossesAmount,
      lossesUnit,
      messageCost,
      isTax
    } = this.state;

    if (!freightConsignorPer) {
      this.setState({ isSubmit: true });
      return;
    }

    if (freightConsignorPer && freightUnit[0] === '') {
      msg.emit('app:tip', { text: '请选择运费单位' });
      return;
    }

    if (lossesAmount === '' && lossesUnit[0] === '') {
      msg.emit('app:tip', { text: '请选择损耗费单位' });
      return;
    }

    onChangeVal({
      type: 'supply',
      val: {
        freightConsignorPer, // 运费
        freightUnit: freightUnit[0] || null, // 运费单位
        lossesAmount: lossesAmount || null, // 耗损费
        lossesUnit: lossesUnit[0] || null, // 耗损费单位
        messageCost: messageCost || null, // 信息费
        isTax
      },
    });
    onChangeModal({ type: 'hopeFreightIsShow', val: false });
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
  },
  mask: {
    width: screenWidth,
    height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    position: 'absolute',
    left: 0,
    top: 0,
  },
  infoContainer: {
    width: screenWidth,
    maxHeight: 0.8 * screenHeight,
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    bottom: 0,
    left: 0,
    borderRadius: px2dp(12),
    overflow: 'hidden',
    zIndex: 10,
  },
  header: {
    width: screenWidth,
    height: px2dp(108),
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
  },
  cancel: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 80,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  editContainer: {
    paddingHorizontal: px2dp(32),
    paddingBottom: px2dp(100),
    maxHeight: screenHeight * 0.5,
  },
  goodsWrapPriceTextInput: {
    fontSize: px2dp(28),
    height: px2dp(88),
    // width: px2dp(296),
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    paddingTop: 0,
    paddingBottom: 0,
  },
  packing: {
    marginTop: px2dp(48),
  },
  itemSelect: {
    marginTop: px2dp(24),
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
  },
  itemHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  itemInput: {
    marginTop: px2dp(24),
    paddingHorizontal: px2dp(24),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
  },
  moreInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: px2dp(60)
  },
  moreInfoText: {
    fontSize: px2dp(28),
    color: fontColorDeepGray
  },
  moreInfoImage: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(10)
  }
});
